package com.css.fxfzxczh.modules.fastDisasterAnalysis.fastSeismicInfluence.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.css.fxfzxczh.base.remote.RemoteService;
import com.css.fxfzxczh.base.response.RestResponse;
import com.css.fxfzxczh.common.utils.ZipDownloadUtil;
import com.css.fxfzxczh.modules.fastDisasterAnalysis.fastSeismicInfluence.entity.FastSeismicInfluence;
import com.css.fxfzxczh.modules.fastDisasterAnalysis.fastSeismicInfluence.entity.FastSiVersion;
import com.css.fxfzxczh.modules.fastDisasterAnalysis.fastSeismicInfluence.entity.IntensityAttenuation;
import com.css.fxfzxczh.modules.fastDisasterAnalysis.fastSeismicInfluence.service.IntensityAttenuationService;
import com.css.fxfzxczh.modules.fastDisasterAnalysis.fastSeismicInfluence.vo.IntensityAttenuationVO;
import com.css.fxfzxczh.modules.fastDisasterAnalysis.fastSeismicInfluence.vo.QueryVO;
import com.css.fxfzxczh.modules.hypergraph.service.HypergraphService;
import com.css.fxfzxczh.util.FileUploadUtil;
import com.css.fxfzxczh.util.PlatformObjectUtils;
import com.css.fxfzxczh.util.PlatformPageUtils;
import com.css.fxfzxczh.util.ResponseCreator;
import com.css.fxfzxczh.web.PlatformSessionContext;
import io.swagger.v3.oas.annotations.Operation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Dbj
 * @date 2022年10月05日  14:01
 * 地震烈度衰减关系模型
 */
@RestController
@Validated
@RequestMapping("/intensity")
public class IntensityAttenuationController {

    @Value("${jcsj.url}")
    private String jcsjUrl;
    @Value("${fxfzypg.url}")
    private String fxfzypgUrl;
    //超图导出文件路径
    @Value("${hypergraph.filePath}")
    String filePath;

    @Resource
    RemoteService remoteService;
    @Resource
    IntensityAttenuationService intensityAttenuationService;
    @Resource
    HypergraphService hypergraphService;

    /***
     * 地震烈度衰减关系模型列表分页查询
     * @param vo
     */
    @GetMapping("/page")
    public RestResponse getPage(IntensityAttenuationVO vo, HttpServletRequest request){
        RestResponse restResponse = null;
        try {
            int curPage = Integer.parseInt(request.getParameter(PlatformPageUtils.CUR_PAGE));
            int pageSize = Integer.parseInt(request.getParameter(PlatformPageUtils.PAGE_SIZE));
            String userId = PlatformSessionContext.getUserID();
            String url = fxfzypgUrl + "/intensity/pageForXczh?page="+curPage+"&rows="+pageSize
                    +"&modelName="+vo.getModelName()+"&province="+vo.getProvince()+"&city="+vo.getCity();
            JSONObject valueMap = new JSONObject();
            JSONObject jsonObject = (JSONObject) remoteService.getJCSJ(url, 2, valueMap).getData();
            String rows = jsonObject.getString("rows");
            List<IntensityAttenuation> list = JSON.parseArray(rows, IntensityAttenuation.class);
            Integer total = Integer.valueOf(jsonObject.getString("total"));
            Map<String, Object> page = new HashMap<String, Object>();
            page.put("total", total);
            page.put("rows", list);
            return ResponseCreator.createSuccessResponse(page,"查询成功!");
        } catch (Exception e) {
            e.printStackTrace();
            restResponse = RestResponse.fail("获取失败！");
        }
        return restResponse;
    }

    /***
     * 地震烈度衰减关系模型根据模型id查询信息
     * @param id
     */
    @GetMapping("/getModelById")
    public RestResponse getModelById(@NotBlank(message="模型id不能为空") @RequestParam("id") String id){
        RestResponse restResponse = null;
        try {
            String url = fxfzypgUrl + "/intensity/getModelById?id="+id;
            JSONObject valueMap = new JSONObject();
            JSONObject jsonObject = (JSONObject) remoteService.getJCSJ(url, 2, valueMap).getData();
            IntensityAttenuation model = JSON.parseObject(jsonObject.toJSONString(),IntensityAttenuation.class);
            return ResponseCreator.createSuccessResponse(model);
        } catch (Exception e) {
            e.printStackTrace();
            restResponse = RestResponse.fail("获取失败！");
        }
        return restResponse;
    }

    /***
     * 断层版本查询
     */
    @GetMapping("/faultVersionPage")
    public RestResponse getFaultVersionPage(HttpServletRequest request,@RequestParam String versionCode,
                                            @RequestParam String uploadStartTime, @RequestParam String uploadEndTime, @RequestParam String uploadUsername){
        RestResponse restResponse = null;
        try {
            int curPage = Integer.parseInt(request.getParameter(PlatformPageUtils.CUR_PAGE));
            int pageSize = Integer.parseInt(request.getParameter(PlatformPageUtils.PAGE_SIZE));
            String url = jcsjUrl + "/datacenter/sysDataVersion/page?dataType2=93";
            url += "&page="+curPage+"&rows="+pageSize+"&hasNationwide=1&versionCode="+versionCode+"&uploadStartTime="+uploadStartTime+"&uploadEndTime="+uploadEndTime+"&uploadUsername="+uploadUsername;
            JSONObject valueMap = new JSONObject();
            restResponse = remoteService.getJCSJ(url, 2, valueMap);
            restResponse.setMessage("获取成功！");
        } catch (Exception e) {
            e.printStackTrace();
            restResponse = RestResponse.fail("获取失败！");
        }
        return restResponse;
    }

    /*快速生成地震影响场*/
    @PostMapping("/countEqIntensity")
    public RestResponse countEqIntensity(@RequestBody FastSiVersion fastSiVersion){
        RestResponse restResponse = null;
        try {
            String modelId = fastSiVersion.getModelId();//模型ID
            //查询模型
            String url = fxfzypgUrl + "/intensity/getModelById?id="+modelId;
            JSONObject valueMap = new JSONObject();
            JSONObject jsonObject = (JSONObject) remoteService.getJCSJ(url, 2, valueMap).getData();
            IntensityAttenuation model = JSON.parseObject(jsonObject.toJSONString(),IntensityAttenuation.class);
            restResponse = intensityAttenuationService.countEqIntensity(fastSiVersion,modelId,model);
        }catch (Exception e){
            e.printStackTrace();
            restResponse = RestResponse.fail("快速生成地震影响场失败！");
        }
        return restResponse;
    }

    /*根据版本ID查询地震影响场空间数据列表*/
    @PostMapping("/getFastSeismicInfluenceListByFvId")
    public RestResponse getFastSeismicInfluenceListByFvId(@RequestBody QueryVO queryVO){
        RestResponse restResponse = null;
        try {
            List<FastSeismicInfluence> fastSeismicInfluenceList = intensityAttenuationService.getFastSeismicInfluenceListByFvId(queryVO.getFvId(),queryVO.getGeom());
            restResponse = RestResponse.succeed(fastSeismicInfluenceList);
            restResponse.setMessage("查询成功！");
        }catch (Exception e){
            e.printStackTrace();
            restResponse = RestResponse.fail("查询失败！");
        }
        return restResponse;
    }

    /*根据版本ID查询地震影响场空间数据以及版本数据列表*/
    @PostMapping("/getFastSeiInfAndVerListByFvId")
    public RestResponse getFastSeiInfAndVerListByFvId(@RequestBody QueryVO queryVO){
        RestResponse restResponse = null;
        try {
            List<IntensityAttenuationVO> fastSeismicInfluenceList = intensityAttenuationService.getFastSeiInfAndVerListByFvId(queryVO.getFvId(),queryVO.getGeom());
            restResponse = RestResponse.succeed(fastSeismicInfluenceList);
            restResponse.setMessage("查询成功！");
        }catch (Exception e){
            e.printStackTrace();
            restResponse = RestResponse.fail("查询失败！");
        }
        return restResponse;
    }

    /*根据版本ID查询地震影响场版本信息*/
    @GetMapping("/getFastSiVersionByFvId")
    public RestResponse getFastSiVersionByFvId(String fvId){
        RestResponse restResponse = null;
        try {
            FastSiVersion fastSiVersion = intensityAttenuationService.getFastSiVersionByFvId(fvId);
            restResponse = RestResponse.succeed(fastSiVersion);
        }catch (Exception e){
            e.printStackTrace();
            restResponse = RestResponse.fail("查询失败！");
        }
        return restResponse;
    }

    /*根据事件ID查询地震影响场版本信息列表*/
    @GetMapping("/getFastSiVersionListByXsemId")
    public RestResponse getFastSiVersionListByXsemId(String xsemId, HttpServletRequest request){
        RestResponse restResponse = null;
        try {
            int curPage = Integer.parseInt(request.getParameter(PlatformPageUtils.CUR_PAGE));
            int pageSize = Integer.parseInt(request.getParameter(PlatformPageUtils.PAGE_SIZE));
            Map<String,Object> page = intensityAttenuationService.getFastSiVersionListByXsemId(xsemId, curPage, pageSize);
            restResponse = RestResponse.succeed(page);
            restResponse.setMessage("查询成功！");
        }catch (Exception e){
            e.printStackTrace();
            restResponse = RestResponse.fail("查询失败！");
        }
        return restResponse;
    }

    /*保存快速生成地震影响场空间数据*/
    @PostMapping("/saveFastSeismicInfluence")
    public RestResponse saveFastSeismicInfluence(@RequestBody FastSeismicInfluence entity){
        RestResponse restResponse = null;
        try {
            intensityAttenuationService.saveFastSeismicInfluence(entity);
            restResponse = RestResponse.succeed("保存成功！");
        }catch (Exception e){
            e.printStackTrace();
            restResponse = RestResponse.fail("保存失败！");
        }
        return restResponse;
    }

    /*保存快速生成地震影响场版本信息*/
    @PostMapping("/saveFastSiVersion")
    public RestResponse saveFastSiVersion(@RequestBody FastSiVersion entity){
        RestResponse restResponse = null;
        try {
            intensityAttenuationService.saveFastSiVersion(entity);
            restResponse = RestResponse.succeed("保存成功！");
        }catch (Exception e){
            e.printStackTrace();
            restResponse = RestResponse.fail("保存失败！");
        }
        return restResponse;
    }

    /*更新快速生成地震影响场版本信息（更新上传图片附件id）*/
    @PostMapping("/updateFastSiVersion")
    public RestResponse updateFastSiVersion(@RequestBody FastSiVersion entity){
        RestResponse restResponse = null;
        try {
            intensityAttenuationService.updateFastSiVersion(entity);
            restResponse = RestResponse.succeed("保存成功！");
        }catch (Exception e){
            e.printStackTrace();
            restResponse = RestResponse.fail("保存失败！");
        }
        return restResponse;
    }

    /**
     * 删除快速生成地震影响场版本信息及地震影响场空间数据列表
     *
     * @param fvId
     * @return
     */
    @PostMapping("/delFastSiVersion/{fvId}")
    public RestResponse delFastSiVersion(@PathVariable("fvId") String fvId) {
        try {
            intensityAttenuationService.delFastSiVersion(fvId);
            return RestResponse.succeed("删除成功");
        } catch (Exception e) {
            return RestResponse.fail("删除数据失败!");
        }
    }

    /*调查任务管理--根据事件ID查询选择的地震影响场版本信息*/
    @GetMapping("/getFastSiVersionByXsemId")
    public RestResponse getFastSiVersionByXsemId(String xsemId){
        RestResponse restResponse = null;
        try {
            FastSiVersion fastSiVersion = intensityAttenuationService.getFastSiVersionByXsemId(xsemId);
            restResponse = RestResponse.succeed(fastSiVersion);
            restResponse.setMessage("查询成功！");
        }catch (Exception e){
            e.printStackTrace();
            restResponse = RestResponse.fail("查询失败！");
        }
        return restResponse;
    }

    /*调查任务管理--根据类型查询事件的全部新建的评估子区数量*/
    @GetMapping("/countSurTaskManageByType")
    public RestResponse countSurTaskManageByType(String xsemId,String type){
        RestResponse restResponse = null;
        try {
            int count = intensityAttenuationService.countSurTaskManageByType(xsemId,type);
            restResponse = RestResponse.succeed(count);
            restResponse.setMessage("查询成功！");
        }catch (Exception e){
            e.printStackTrace();
            restResponse = RestResponse.fail("查询失败！");
        }
        return restResponse;
    }

    /**
     * 调查任务管理--根据事件ID设置全部快速生成地震影响场版本信息未选择、删除全部新建的评估子区
     *
     * @param xsemId
     * @return
     */
    @PostMapping("/setUnselectFastSiVersionDeleteTaskByXsemId/{xsemId}/{fvId}")
    public RestResponse setUnselectFastSiVersionDeleteTaskByXsemId(@PathVariable("xsemId") String xsemId,@PathVariable("fvId") String fvId) {
        try {
            //调查任务管理--事件的全部快速生成地震影响场版本信息设置未选择
            intensityAttenuationService.unSelectFastSiVersion(xsemId);
            //调查任务管理--根据事件ID删除全部新建的评估子区
            intensityAttenuationService.deleteSurTaskManageType0(xsemId);
            return RestResponse.succeed("删除成功");
        } catch (Exception e) {
            return RestResponse.fail("删除数据失败!");
        }
    }

    /**
     * 调查任务管理--事件的1个快速生成地震影响场版本信息设置选择
     *
     * @param fvId
     * @return
     */
    @PostMapping("/setSelectFastSiVersion/{xsemId}/{fvId}")
    public RestResponse setSelectFastSiVersion(@PathVariable("xsemId") String xsemId,@PathVariable("fvId") String fvId) {
        try {
            //调查任务管理--事件的全部快速生成地震影响场版本信息设置未选择
            intensityAttenuationService.unSelectFastSiVersion(xsemId);
            //调查任务管理--事件的1个快速生成地震影响场版本信息设置选择
            intensityAttenuationService.setSelectFastSiVersion(fvId);
            return RestResponse.succeed("设置成功");
        } catch (Exception e) {
            return RestResponse.fail("设置失败!");
        }
    }

    /**
     * 批量下载文件shp
     *
     * @param response
     * @return
     */
    @PostMapping("/downloadSpaceFile")
    public RestResponse downloadSpaceFile(HttpServletResponse response, String affiliatedFileName) {
        String newUploadPath = filePath;
        //获取指定路径下的所有文件名
        File file = new File(newUploadPath);
        File[] files = file.listFiles();
        if (files == null) {
            return RestResponse.fail("下载失败，该目录下不存在文件");
        }
        String tempFileName = affiliatedFileName;
        String _temp = "";
        List<File> _files = new ArrayList<>();
        for (int i = 0; i < files.length; i++) {
            _temp = files[i].getName();
            if (_temp.indexOf(tempFileName) != -1) _files.add(files[i]);
        }
        List<File> zipFiles = _files;
        //List<File> zipFiles = new ArrayList<>(Arrays.asList(files));
        StringBuffer sb = new StringBuffer();
        if (!CollectionUtils.isEmpty(zipFiles)) {
            String zipName = tempFileName + ".zip";
            String msg = ZipDownloadUtil.zipDownload(response, newUploadPath, zipName, zipFiles);
            sb.append(msg);
        } else {
            /*sb.append("没有可下载文件");
            return RestResponse.succeed(sb);*/
            String zipName = tempFileName + ".zip";
            String msg = ZipDownloadUtil.zipDownload(response, newUploadPath, zipName, new ArrayList<File>());
            sb.append(msg);
        }

        return null;
        //return RestResponse.succeed(sb);
    }

    //根据sql导出shp文件并下载zip
    @PostMapping("/downloadShpFileBySql")
    public RestResponse downloadShpFileBySql(HttpServletResponse response, String dataset, String sqlFilter) {
        try {
            String timeStamp = System.currentTimeMillis() + "";//时间戳，用于数据集名称后缀，防止重名
            String datasource = "fxfzxczh";
            if(dataset.equals("jc_fault")){
                datasource = "datacenter";//基础数据系统
            }
            //导出shp文件
            String resultFilePath = hypergraphService.exportShpFile(datasource,dataset,sqlFilter,timeStamp);
            if (PlatformObjectUtils.isEmpty(resultFilePath)) {
                return RestResponse.fail("导出失败!");
            }else{
                String affiliatedFileName = dataset;
                //获取指定路径下的所有文件名
                File file = new File(resultFilePath);
                File[] files = file.listFiles();
                if (files == null) {
                    return RestResponse.fail("下载失败，该目录下不存在文件");
                }
                String tempFileName = affiliatedFileName;
                String _temp = "";
                List<File> _files = new ArrayList<>();
                for (int i = 0; i < files.length; i++) {
                    _temp = files[i].getName();
                    if (_temp.indexOf(tempFileName) != -1) _files.add(files[i]);
                }
                List<File> zipFiles = _files;
                //List<File> zipFiles = new ArrayList<>(Arrays.asList(files));
                StringBuffer sb = new StringBuffer();
                if (!CollectionUtils.isEmpty(zipFiles)) {
                    String zipName = tempFileName + ".zip";
                    String msg = ZipDownloadUtil.zipDownload(response, resultFilePath, zipName, zipFiles);
                    sb.append(msg);
                } else {
                    String zipName = tempFileName + ".zip";
                    String msg = ZipDownloadUtil.zipDownload(response, resultFilePath, zipName, new ArrayList<File>());
                    sb.append(msg);
                }
            }

            return RestResponse.succeed("导出成功");
        } catch (Exception e) {
            return RestResponse.fail("导出失败!");
        }
    }


    /*//下载文件tif
    @PostMapping("/downloadTifFile")
    public RestResponse downloadTifFile(HttpServletResponse response, String tifFileName) {
        String path = filePath + tifFileName + ".tif";
        FileUploadUtil.download(path, response);

        return null;
    }*/

    //下载文件tif
    @PostMapping("/downloadTifFile")
    public RestResponse downloadTifFile(HttpServletResponse response, String tifFilePath) {
        String path = tifFilePath;
        FileUploadUtil.download(path, response);

        return null;
    }
}
